//
//  EDSVideoPreviewViewController.m
//  DrivieSchoolStudents
//
//  Created by TangBin on 2019/5/23.
//  Copyright © 2019 班文政. All rights reserved.
//

#import "EDSVideoPreviewViewController.h"
#import "EDSVideoPreviewView.h"
#import "EDSVideoPreviewBottomView.h"
#import "EDSNavBarView.h"

@interface EDSVideoPreviewViewController ()

@property (nonatomic, strong) EDSNavBarView *navBarView;

@property (nonatomic, strong) EDSVideoPreviewBottomView *bottomView;

@property (nonatomic, strong) EDSVideoPreviewView *previewView;

/**
 *  是否获取了视频长度
 */
@property (nonatomic, assign) BOOL isFetchTotalDuration;

@property (nonatomic, strong) id timeObserver;

@property (nonatomic, assign) NSTimeInterval bufferTime;


/**
 *  是否正在缓冲
 */
@property (nonatomic, assign) BOOL isBuffering;

@property (nonatomic, assign) BOOL isFinishedJump;

@property (nonatomic, assign) NSTimeInterval currentPlayTime;

@property (nonatomic, assign) NSTimeInterval currentBufferTime;

@property (nonatomic, assign) NSTimeInterval durationTime;

- (void)initWithNavBarView;

- (void)initWithBottomView;

- (void)initWithPreviewView;

@end

@implementation EDSVideoPreviewViewController

- (void)dealloc
{
    NSLog(@"%s", __func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)initWithVar
{
    [super initWithVar];
    
    self.isBuffering = YES;
}

- (void)initWithNavBar
{
    [super initWithNavBar];
    
    [self initWithBackButton];
    
    
    
    // 裁剪的情况下，是不可以删除视频的；录制完成后，预览是可以删除视频的
    if (!self.isShowCrop)
    {
        UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
        btnRight.frame = CGRectMake(0, 0, 40, 30);
        [btnRight setTitle:@"删除" forState:UIControlStateNormal];
        [btnRight setTitleColor:[UIColor colorWithHexString:@"#FF4545"] forState:UIControlStateNormal];
        btnRight.titleLabel.font = [UIFont systemFontOfSize:14];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
        self.navigationItem.rightBarButtonItem = rightItem;
        @weakify(self);
        [[btnRight rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self.previewView stopPlay];
            if (self.removeVideoBlock)
            {
                self.removeVideoBlock(self.videoUrl, self);
            }
        }];
    }
//    else
//    {
//        self.navigationController.navigationBarHidden = YES;
//        self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#262625"];
//    }
}

- (void)initWithSubView
{
    [super initWithSubView];
    
    [self initWithNavBarView];
    
    [self initWithPreviewView];
    
    [self initWithBottomView];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.previewView.player.currentItem];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    if (self.isShowCrop)
    {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.isShowCrop)
    {
        self.navigationController.navigationBarHidden = YES;
    }
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#262625"];
}

- (void)initWithNavBarView
{
    if (!_navBarView)
    {
        CGRect frame = CGRectMake(0, 0, kScreenWidth, NAVBAR_HEIGHT_STATUS);
        _navBarView = [[EDSNavBarView alloc] initWithFrame:frame];
        _navBarView.backgroundColor = [UIColor colorWithHexString:@"#262625"];
        [self.view addSubview:_navBarView];
        @weakify(self);
        _navBarView.touchBackBlock = ^{
            @strongify(self);
            [self clickedBack:nil];
        };
    }
}

- (void)initWithPreviewView
{
    if (!_previewView)
    {
        CGRect frame = self.view.bounds;
        if (self.isShowCrop)
        {
            frame.origin.y = _navBarView.bottom;
            frame.size.height = kScreenHeight - TABBAR_HEIGHT - NAVBAR_HEIGHT_STATUS;
        }
        _previewView = [[EDSVideoPreviewView alloc] initWithFrame:frame videoUrl:self.videoUrl];
        [self.view addSubview:_previewView];
        
//        [RACObserve(self.passwordTxtField, backgroundColor) subscribeNext:^(id x) {
//            NSLog(@"==%@", x);
//        }]
//        self.previewView.playerItem
//        @weakify(self);
//        // 监听status属性
//        [RACObserve(self.previewView.playerItem, status) subscribeNext:^(id  _Nullable x) {
//            NSLog(@"class=%@", NSStringFromClass([x class]));
//            @strongify(self);
//            [self statusChange:[x integerValue]];
//        }];
//        
//        // 监听loadedTimeRanges属性
//        [RACObserve(self.previewView.playerItem, loadedTimeRanges) subscribeNext:^(id  _Nullable x) {
//            NSLog(@"class=%@", NSStringFromClass([x class]));
//            [self loadedTimeRangesChange];
//        }];
    }
    
    
    
}

- (void)clickedBack:(id)sender
{
    [self.previewView stopPlay];
//    [super clickedBack:sender];
    
    // 把导航栏的背景色设置回去
//    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initWithBottomView
{
    if (!self.isShowCrop)
    {
        return;
    }
    if (!_bottomView)
    {
//        kNAVBAR_HEIGHT
        CGRect frame = CGRectMake(0, self.previewView.bottom, kScreenWidth, TABBAR_HEIGHT);
        _bottomView = [[EDSVideoPreviewBottomView alloc] initWithFrame:frame leftTitle:@"剪辑" rightTitle:@"完成"];
        [self.view addSubview:_bottomView];
        [_bottomView updateVideoTime:self.model.seconds];
        @weakify(self);
        // 裁剪按钮事件
        [[_bottomView.btnCrop rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
//            UIViewController *cropVC = [[TYZRouter sharedInstance] getVideoCropVC:@{@"model":self.model}];
//            [TYZJumpVCManager pushBaseVC:self pushVC:cropVC];
        }];
        
        // 完成按钮事件
        [[_bottomView.btnFinished rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
//            NSLog(@"发送通知=%@", [NSThread currentThread]);
            [[NSNotificationCenter defaultCenter] postNotificationName:kVIDEO_CLIP_FINISHED_NOTI object:self.model];
        }];
        
    }
}

/*
 AVPlayerItem有两个很重要的属性，一个是status，一个是loadedTimeRanges。使用kvo监听status属性值的改变，当status变为
 　　AVPlayerStatusReadyToPlay的时候，表示可以开始播放了。而监听loadedTimeRanges属性，可以知道视频缓存到哪样一个时间点了：
 */

/**
 状态改变的时候

 @param status status description
 */
- (void)statusChange:(NSInteger)status
{
    NSLog(@"status=%d", (int)status);
    @weakify(self);
    if (status == AVPlayerStatusReadyToPlay)
    {// 表示可以播放了
        self.timeObserver = [self.previewView.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            @strongify(self);
            NSTimeInterval currentTime = CMTimeGetSeconds(time);
            self.currentPlayTime = currentTime;
        }];
    }
}

/**
 在这段代码里面，我是设置了，如果当前播放时间+10s > 缓冲得到的总时间，那么就loading，直到缓冲时间总是大于当前播放时间10s，才开始播放。
 */
- (void)loadedTimeRangesChange
{// 缓冲
    // 可用的播放时长(缓冲的时长)
    self.bufferTime = [self availableBufferTime];
    if (!self.isFetchTotalDuration)
    {
        // 获取视频总长度
        NSTimeInterval totalDuration = CMTimeGetSeconds(self.previewView.playerItem.duration);
        NSLog(@"totalDuration=%f", totalDuration);
        self.durationTime = totalDuration;
        self.isFetchTotalDuration = YES;
    }
    
    if (self.currentPlayTime <= self.durationTime - 7)
    {
        // 如果缓冲不够
        if (self.bufferTime <= self.currentPlayTime + 5)
        {
            self.isBuffering = YES;
        }
        else
        {
            self.isBuffering = NO;
        }
    }
    else
    {
        self.isBuffering = NO;
    }
    self.currentBufferTime = self.bufferTime;
}

/**
 *  可用的播放时长(缓冲的时长)
 *
 */
- (NSTimeInterval)availableBufferTime
{
    NSArray *loadTimeRanges = [[self.previewView.player currentItem] loadedTimeRanges];
    
    //获取缓冲区域
    CMTimeRange range = [loadTimeRanges.firstObject CMTimeRangeValue];
    
    NSTimeInterval startTime = CMTimeGetSeconds(range.start);
    
    NSTimeInterval duration = CMTimeGetSeconds(range.duration);
    
    return startTime + duration;
}

/**
 收到播放完成的通知
 
 @param note note description
 */
- (void)playbackFinished:(NSNotification *)note
{
    //    Plog(@"视频播放完成");
//    self.isPlaying = NO;
//    self.playImgView.hidden = NO;
//    [self.player seekToTime:CMTimeMake(0, 1)];
    //    [self.player play];
    self.isFetchTotalDuration = NO;
    @weakify(self);
    [self.previewView.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        @strongify(self);
        self.currentPlayTime = 0;
        self.currentBufferTime = 0;
        self.durationTime = 0;
    }];
    
}


@end






















